//
//  LRUserAccountVM.swift
//  WeiboX
//
//  Created by admin on 04/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit

class LRUserAccountVM: NSObject {
	
	// 单例的全局访问点
	static let sharedUserAccount: LRUserAccountVM = LRUserAccountVM()
	
	// 是否登录的标记
	var isLogin: Bool {
		return accessToken != nil
	}
	
	// 用户帐号模型
	var userAccount: LRUserAccount? {
		return LRUserAccount.loadUserInfo()
	}
	
	//  获取accesstoken的逻辑
	/*
	1. 判断accesstoken是否为nil, 如果为nil, 直接返回nil
	2. 如果不为nil, 判断accesstoken的过期时间是否大于我们的当前时间,如果过期时间大于我们的当前时间表示没有过期, 返回accesstoken, 否则 表示过期了, 那么返回nil
	*/
	var accessToken: String? {
		guard let accessToken = userAccount?.access_token else {
			return nil
		}
		
		if userAccount?.expiresDate?.compare(Date()) == ComparisonResult.orderedDescending {
			return accessToken
		} else {
			return nil
		}
		
	}
	
	
	func requestAccessToken(code: String, callBack: @escaping (Bool) -> ()) {
		LRNetworkManager.sharedManager.requestAccessToken(code: code) { (responseObj, error) in
			if error != nil {
				print(error!)
			}
			
			//			print(responseObj)
			let dic = responseObj as! [String: Any]
			
			let userAccount = LRUserAccount(dic: dic)
//			print(userAccount)
			
			self.requestUserInfo(userInfo: userAccount, callBack: callBack)
		}
	}
	
	private func requestUserInfo(userInfo: LRUserAccount, callBack: @escaping (Bool) -> ()) {
		let accessToken = userInfo.access_token
		let uid = userInfo.uid
		
		LRNetworkManager.sharedManager.requestUserInfo(accesToken: accessToken!, uid: uid) { (responseObj, error) in
			if error != nil {
				print(error!)
			}
			
			
			let dic = responseObj as! [String: Any]
			let name = dic["name"]
			let avatar_large = dic["avatar_large"]
			
			userInfo.name = name as! String?
			userInfo.avatar_large = avatar_large as! String?
			
			// 登录成功, 归档属性
			userInfo.saveUserInfo()
			
			// 闭包返回 成功
			callBack(true)
		}
	}

}
